#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDebug>
#include <QDateTime>
#include <QFile>
#include <QDialog>
#include <QLabel>
#include <QPixmap>

#define PIXMAP_SIZE 100

MainWindow::MainWindow(QWidget *parent) :
  QMainWindow(parent),
  ui_(new Ui::MainWindow),
  sg_("items.txt")
{
  ui_->setupUi(this);
}

MainWindow::~MainWindow()
{
  delete ui_;
}

void MainWindow::on_random_clicked()
{
  for (std::vector<QWidget *>::iterator it = shelves_.begin (); it != shelves_.end (); ++it)
  {
    (*it)->hide();
    ui_->shelves_layout->removeWidget (*it);
  }

  QLayoutItem *child;
  while ((child = ui_->shelves_layout->takeAt(0)) != 0) {
    delete child;
  }

  QString filename = QDateTime::currentDateTime ().toString () + ".log";
  QFile file(filename);
  if (file.open (QIODevice::ReadWrite | QIODevice::Text))
  {
    qCritical("Cannot create log file");
    return;
  }

  sg_.generate ();

  QTextStream fs(&file);

  for (int region_idx = 0; region_idx < REGIONS; region_idx++)
  {
      QWidget *shelf = new QWidget;
      ui_->shelves_layout->addWidget (shelf);
      shelves_.push_back (shelf);

      QGridLayout *layout = new QGridLayout;
      shelf->setLayout (layout);

      QString str;
      for (int number_idx = 0; number_idx < NUMBERS; number_idx++)
      {
          std::string region(" ");
          region[0] = 'A' + region_idx;
          QString name;
          name = QString::fromStdString (sg_(region, 1 + number_idx));
          QLabel *widget = new QLabel;

          if (name.isEmpty ())
          {
              str += "(null)";
          }
          else
          {
              QString image_filename = "images/" + name + ".png";
              QPixmap pixmap(image_filename);

              if (pixmap.isNull ())
                  qCritical() << "Cannot open image file: " << image_filename;
              else
              {
                  pixmap = pixmap.scaled (PIXMAP_SIZE, PIXMAP_SIZE);

                  widget->setPixmap (pixmap);
              }
              str += name;
          }

          layout->addWidget ((QWidget *)widget, number_idx % 2, number_idx / 2, 1, 1);

          str += "\t";
      }

      qDebug() << str;
      fs << str << "\n";
  }

  file.close ();
}
